package fyp.spedmew.backend.service;

import com.google.api.server.spi.response.NotFoundException;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import fyp.spedmew.backend.entity.Job;
import fyp.spedmew.backend.entity.JobEndpoint;

/**
 * Handle file upload from android client
 */
public class FileUploadServlet extends HttpServlet{
    private BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();

    private static final Logger log = Logger.getLogger(FileUploadServlet.class.getName());

    @Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        Long jobId = Long.valueOf(req.getParameter("jobId"));
        String imgKey;
        Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(req);
        List<BlobKey> blobKeys = blobs.get("myFile");

        if (blobKeys == null || blobKeys.isEmpty()) {
            res.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            log.info("Blob key is empty");
        } else {
            res.setStatus(HttpServletResponse.SC_OK);
            imgKey = blobKeys.get(0).getKeyString();
            saveImageId(jobId, imgKey);
            log.info("Blob key " + imgKey);
        }
    }

    private Boolean saveImageId(Long jobId, String imgKey) {
        JobEndpoint ep = new JobEndpoint();
        Job job = ep.findRecord(jobId);
        if (job != null) {
            job.setImgKey(imgKey);
            try {
                ep.updateJob(job);
            } catch (NotFoundException e) {
                log.warning(e.toString());
                return Boolean.FALSE;
            }
            return Boolean.TRUE;
        } else {
            return Boolean.FALSE;
        }
    }
}
